package com.szwistar.common.comm;

import java.nio.ByteOrder;
import org.apache.mina.core.buffer.IoBuffer;

import com.szwistar.common.datastruct.Utils;

public class ZktAck extends ZktFrame implements AsyncResponse {
	public static final short ACK_OK   = 2000;

	// 本消息的接收者
	AsyncTranceiver receiver;
	@Override
	public AsyncTranceiver getReceiver() { return receiver; }
	@Override
	public void setReceiver(AsyncTranceiver receiver) { this.receiver = receiver; }

	@Override
	public Object getSource() { return (receiver == null) ? null : receiver.getOwner(); }
	@Override
	public Object getTarget() { return (receiver == null) ? null : receiver.getOwner(); }

	public ZktAck(short cmd, short sessionId, short fsn, byte[] bytes) {
		super(cmd, sessionId, fsn, bytes);
	}

	public static ZktAck decode(IoBuffer buf) throws Exception {
		buf.order(ByteOrder.LITTLE_ENDIAN);
		int init = buf.position();
		int len = buf.getInt() - 8;
		int cmd = buf.getUnsignedShort();
		buf.getUnsignedShort();	// sum
		int sessionId = buf.getUnsignedShort();
		int fsn = buf.getUnsignedShort();
		byte[] bytes = null;
		if(len > 0) {
			bytes = new byte[len];
			buf.get(bytes);
		}

		if(sum(buf, init+4, 8+len) != -1) {
			throw new Exception("ZktFrame 帧校验错误！");
		}

		return new ZktAck((short)cmd, (short)sessionId, (short)fsn, bytes);
	}

	@Override
	public String toString() {
		return "ZktAck [err=" + cmd + ", sessionId=" + sessionId + ", fsn=" + fsn + ", bytes=" + Utils.bytesToHexString(bytes) + "]";
	}
}
